package com.chinackts.auth.repository.redis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author Lianhong
 * @since 2022/4/21
 */
@Repository
public class ICCardRepository {

    @Resource
    private StringRedisTemplate redisTemplate1;

    private static final String KEY = "%s:icCard";

    @Value("${e-port.redis.timeout}")
    private long timeout;


    public String key(String id) {
        return String.format(KEY, id);
    }

    /**
     * 获取企业税号
     *
     * @param id 用户标识
     */
    public String getIcCard(String id) {
        ValueOperations<String, String> ops = this.redisTemplate1.opsForValue();
        String icCard = ops.get(String.format(KEY, id));
        if (StringUtils.isEmpty(icCard)) return null;
        return icCard;
    }

    public void saveIcCard(String id, String icCard) {
        ValueOperations<String, String> ops = this.redisTemplate1.opsForValue();
        ops.set(String.format(KEY, id), icCard, timeout, TimeUnit.HOURS);
        ops.set(String.format(KEY, id) + ":" + icCard, icCard, timeout, TimeUnit.HOURS);
    }


    public void removeAllByIcCard(String id, String icCard) {
        //模糊匹配对应口岸卡卡号下所有的 key
        Set<String> keys = redisTemplate1.keys("*:icCard:" + icCard);
        if (keys == null || keys.isEmpty()) return;
        Set<String> idKeys = new HashSet<>();
        //取key的第一层（用户ID标识）
        keys.forEach(item -> idKeys.add(item.split(":")[0]));
        //排除本次登录完成的用户ID
        idKeys.removeIf(item -> item.equals(id));
        //清除之前登录的用户ID下的所有缓存数据
        idKeys.forEach(item -> {
            Set<String> allKeys = redisTemplate1.keys(item + ":*");
            if (allKeys == null || allKeys.isEmpty()) return;
            redisTemplate1.delete(allKeys);
        });
    }

}
